<?php
/**
 * Created by Zend Studio.
 * User: FDG348
 * Date: 2017/9/6
 * Time: 10:35
 */

namespace backend\controllers;

use yii\web\AdminController;
use Yii;
use backend\models\SysMessageTemplate;
use backend\models\SysConfig;

class SysMessageController extends AdminController{
    public $layout = false;
    //业务关键字
    public $service = 'SysMessageTemplate';

    /**
     * 消息模板查询页面
     * @return string
     */
    public function actionIndex(){
        $config = SysConfig::find()->select('config_title,config_key,config_value')->where("use_flg=1 and config_group_id = 'gp_message_template'")->asArray()->all();
        //$template_type = $GLOBALS['_SMS_MESSAGE_TYPE'];
        $template_type = array('1'=>'短信','2'=>'站内信','3'=>'邮件');
        $this->saveLog($this->service,'消息模板查询','VIEW', '');
        return $this->render('index',['config'=>$config,'template_type'=>$template_type]);
    }
    
    public function actionGetMessageTemplate(){
        $data = Yii::$app->request->post();
        $template = SysMessageTemplate::find()->select('id,template_name,template_key,type,content');
        $title = trim($data['search_template_title']);
        if(!empty($title)){
            $template = $template->where(['like','template_name',$title]);
        }
        $count = $template->count();
        $sort_string = empty($data['columns'][$data['order'][0]['column']]['data']) ? 'id' : $data['columns'][$data['order'][0]['column']]['data'];
        $list = $template->offset($data['start'])->limit($data['length'])->orderBy(
            [$sort_string=>$data['order'][0]['dir'] == 'asc' ? SORT_ASC : SORT_DESC])->asArray()->all();
        $result['draw'] = intval($data['draw']);
        $result['recordsTotal'] = intval($count);
        $result['recordsFiltered'] = intval($count);
        $result['data'] = $list;
        return \yii\helpers\Json::encode($result);
    }

    /**
     * 修改模板数据。
     * @throws \yii\db\Exception
     */
    public function actionChangeMessageTemplate(){
        $message_template = new SysMessageTemplate();
        $data = Yii::$app->request->post();
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $sys_message_template_id = $data['sys_message_template_id'];
            $template_name = trim($data['template_name']);
            $template_key = $data['template_key'];
            $type = $data['type'];
            $content = $data['content'];
            if (!$template_name) {
                throw new \Exception('请填写模板名称');
            }
            if (!$template_key) {
                throw new \Exception('请填写模板别名');
            }
            if (!$type) {
                throw new \Exception('请填写模板类型');
            }
            if (!$content) {
                throw new \Exception('请填写模板内容');
            }
            $operor = $message_template->getCreator();
            $operTime = date('Y-m-d H:i:s');
            if ($sys_message_template_id){
                $message_template = SysMessageTemplate::findOne($sys_message_template_id);
                $has_template_name = SysMessageTemplate::find()->where('template_name=:template_name',[':template_name'=>$template_name])->one();
                if ($has_template_name && $has_template_name->id != $sys_message_template_id){
                    throw new \Exception('该模板名称已存在，不可重复');
                }
                $has_template_key = SysMessageTemplate::find()->where('template_key=:template_key',[':template_key'=>$template_key])->one();
                if ($has_template_key && $has_template_key->id != $sys_message_template_id){
                    throw new \Exception('该模板别名已存在，不可重复');
                }
                $message_template->editor = $operor;
                $message_template->edit_time = $operTime;
                $access_type = 'MOD';
            }else{
                $message_template->creator = $operor;
                $message_template->create_time = $operTime;
                $access_type = 'ADD';
            }
            $message_template->template_name = $template_name;
            $message_template->template_key = $template_key;
            $message_template->type = $type;
            $message_template->content = $content;
            $message_template->save();
            $message_template_id = $message_template->attributes['id'];
            if (!$message_template_id){
                throw new \Exception('操作失败，请重试');
            }
            $transaction->commit();
            $this->saveLog($this->service,'保存模板',$access_type, $template_name . "\r\n" .\yii\helpers\Json::encode($message_template));
            $this->retJson('编辑成功',200);
        }catch (\Exception $e){
            $transaction->rollBack();
            //add by allen.qiang 20180112 异常处理，日志优化 start
            error_log('error->' . __METHOD__ . ' error:' . $e->getMessage());
            //add by allen.qiang 20180112 异常处理，日志优化 end
            $this->retJson($e->getMessage(),500);
        }
    }

    /**
     * 删除模板数据
     * @throws \Exception
     */
    public function actionRemoveMessageTemplate(){
        $data = Yii::$app->request->post();
        $message_template_where = ['id'=>$data['id']];
        $ret = SysMessageTemplate::deleteAll($message_template_where);
        if(!$ret){
            //add by allen.qiang 20180112 异常处理，日志优化 start
            error_log('error->' . __METHOD__ . ' error:操作失败 ');
            //add by allen.qiang 20180112 异常处理，日志优化 end
            throw new \Exception('操作失败');
        }
        $this->saveLog($this->service,'删除模板','DEL', '删除模板 ID='. $data['id']);
        $this->retJson('操作成功',200);
    }
}